package cn.jekun.shop.common.service;

import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.McCreditsJournal;
import cn.jekun.shop.web.bean.MyCredits;
import cn.jekun.shop.web.bean.UserStat;

@Service(MyCreditsService.BEAN_NAME)
public class MyCreditsService extends ShopBaseService{

	public static final String BEAN_NAME = "cn.jekun.shop.common.service.MyCreditsService";
	
	@Override
	public String getNamespace() {
		return "SHOP_MY_CREDITS";
	}
	/**
	 * 我的积分，和积分流水,分页倒序返回积分消费列表
	 * @param userId 用户代码
	 * @param operationTypeId 积分操作类型(可选)
	 * @param endDate 结束日期(可选)
	 * @param page 分页
	 * @return
	 */
	public JSONObject getMyCredits(
			@Security
			String userId,
			@Security
			String operationTypeId,
			@Security
			Date endDate,
			Page page) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
		try{
			Map map = new HashMap();
			map.put("userId", userId);
			
			UserStat userCreditsStat = this.one("SHOP_USER.userCreditsStat", map);//获取用户总积分
			if(userCreditsStat!=null){
				jsonObject.put("creditsTotal", userCreditsStat.getCreditsTotal());//总积分
				jsonObject.put("userName", userCreditsStat.getUserName());//总积分
			}else if (userCreditsStat!=null && userCreditsStat.getCreditsTotal()==null){
				jsonObject.put("creditsTotal", 0.0);//总积分
				jsonObject.put("userName", userCreditsStat.getUserName());
			}else{
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"此用户暂无任何积分流水信息");
			}
			//积分流水
			map.put(McCreditsJournal.COL_OPERATION_TYPE_ID, operationTypeId);
			if (endDate!=null) {
				map.put(McCreditsJournal.COL_CREATE_TIME, DateFormatUtils.format(endDate,"yyyy-MM-dd"));
			}
			SqlUtis.prepareSql(map
					, SqlUtis.getSQL(map, "a."+McCreditsJournal.COL_OPERATION_TYPE_ID)//积分操作类型
					, SqlUtis.getSQL(map, "a."+McCreditsJournal.COL_CREATE_TIME,Types.DATE,SqlUtis.GE)//结束日期
					);
			List<MyCredits> credits = this.list(map,page);
			jsonObject.put("credits", credits);
			jsonObject.put("totalCount", page.getTotalCount());
			jsonObject.put("pages", page.getPages());
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
}
